<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { useRouter } from "vue-router";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElButton,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElInput,
  ElCard,
} from "element-plus";
// 移除不再使用的icon导入
import {
  getIntelligenceHistory,
  getIntelligenceDetail,
  forceIntelligenceCollection,
  uploadIntelligence,
  matchIntelligence,
  recommendPocs,
} from "../servers";

const router = useRouter();

const props = defineProps<{
  task: string;
}>();

const loading = ref(false);
const intelligenceList = ref<any[]>([]);
const searchFormRef = ref<DynamicFormInstance>();

// 筛选统计摘要（根据MD文档设计）
const filterSummary = ref({
  total_matched: 0,
  total_unmatched: 0,
  severity_distribution: {
    critical: 0,
    high: 0,
    medium: 0,
    low: 0,
  },
  applied_filters: {} as any,
});

// 统计信息（兼容旧数据）
const statistics = ref({
  total_count: 0,
  critical_count: 0,
  high_count: 0,
  medium_count: 0,
  low_count: 0,
});

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const searchForm = reactive({
  search_keyword: "", // 🔥 新功能：关键词搜索（情报名称、CVE ID、描述）
  source: "",
  severity: "", // 使用severity替代vul_level以匹配新接口
  has_matched_assets: null as boolean | null, // 🔥 新功能：资产匹配筛选
  time_filter: "", // 🔥 新功能：快速时间筛选
  date_range: null as { start_date?: string; end_date?: string } | null, // 🔥 精确时间范围
  has_poc: undefined as boolean | undefined,
});

const searchConfig: FormItemConfig[] = [
  {
    key: "search_keyword",
    name: "搜索",
    type: "input",
    labelWidth: "60px",
    placeholder: "搜索CVE、产品名称、漏洞名称...",
    params: {
      clearable: true,
    },
  },
  {
    key: "has_matched_assets",
    name: "资产匹配",
    type: "select",
    labelWidth: "80px",
    placeholder: "选择匹配状态",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部情报", value: null },
        { label: "有匹配资产", value: true },
        { label: "无匹配资产", value: false },
      ],
    },
  },
  {
    key: "severity",
    name: "严重程度",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择严重程度",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "严重", value: "critical" },
        { label: "高危", value: "high" },
        { label: "中危", value: "medium" },
        { label: "低危", value: "low" },
      ],
    },
  },
  {
    key: "time_filter",
    name: "时间范围",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择时间范围",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "📅 最近7天", value: "last_7_days" },
        { label: "📅 最近30天", value: "last_30_days" },
        { label: "📅 本月", value: "this_month" },
        { label: "📅 本季度", value: "this_quarter" },
        { label: "📅 本年", value: "this_year" },
      ],
    },
  },
  {
    key: "source",
    name: "来源",
    type: "select",
    labelWidth: "80px",
    placeholder: "选择来源",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "NVD", value: "NVD" },
        { label: "CNVD", value: "CNVD" },
        { label: "自定义", value: "自定义" },
      ],
    },
  },
  {
    key: "has_poc",
    name: "POC",
    type: "select",
    labelWidth: "80px",
    placeholder: "是否有POC",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: undefined },
        { label: "有POC", value: true },
        { label: "无POC", value: false },
      ],
    },
  },
];

const getVulLevelTag = (level: string) => {
  const levelMap: Record<string, any> = {
    严重: { text: "严重", type: "danger" },
    高危: { text: "高危", type: "danger" },
    中危: { text: "中危", type: "warning" },
    低危: { text: "低危", type: "info" },
  };
  return levelMap[level] || { text: level, type: "info" };
};

// 获取风险等级标签（根据MD文档设计）
const getRiskLevelTag = (level: string, hasMatches: boolean) => {
  const levelMap: Record<string, any> = {
    critical: { text: "严重", type: "danger", color: "#ff4d4f" },
    high: { text: "高危", type: "danger", color: "#ff7a45" },
    medium: { text: "中危", type: "warning", color: "#ffa940" },
    low: { text: "低危", type: "success", color: "#52c41a" },
  };
  const levelInfo = levelMap[level] || {
    text: level,
    type: "info",
    color: "#909399",
  };
  return {
    ...levelInfo,
    displayText: hasMatches ? `🎯 ${levelInfo.text}` : levelInfo.text,
  };
};

const columns = ref<TableColumn[]>([
  {
    label: "漏洞名称",
    prop: "vul_name",
    minWidth: 200,
    show: true,
  },
  {
    label: "CVE编号",
    prop: "cve_id",
    width: 150,
    show: true,
    render: (row) => {
      return h("span", { style: { fontWeight: 500 } }, row.cve_id || "-");
    },
  },
  {
    label: "严重程度",
    prop: "severity",
    width: 100,
    show: true,
    render: (row) => {
      const levelInfo = getVulLevelTag(
        row.severity === "critical"
          ? "严重"
          : row.severity === "high"
          ? "高危"
          : row.severity === "medium"
          ? "中危"
          : row.severity === "low"
          ? "低危"
          : row.severity || row.vul_level || ""
      );
      return h(ElTag, { type: levelInfo.type, size: "small" }, levelInfo.text);
    },
  },
  // {
  //   label: "风险等级",
  //   prop: "risk_level",
  //   width: 100,
  //   show: true,
  //   render: (row) => {
  //     const riskLevel = row.risk_level || row.severity || "";
  //     const hasMatches = row.has_matches || row.matched_assets > 0;
  //     const levelInfo = getRiskLevelTag(riskLevel, hasMatches);
  //     return h(
  //       ElTag,
  //       {
  //         type: levelInfo.type,
  //         size: "small",
  //         style: { color: levelInfo.color },
  //       },
  //       levelInfo.displayText
  //     );
  //   },
  // },
  {
    label: "匹配资产",
    prop: "matched_assets",
    width: 120,
    show: true,
    render: (row) => {
      const count = row.matched_assets || 0;
      const hasMatches = row.has_matches || count > 0;
      return h(
        "div",
        { style: { display: "flex", alignItems: "center", gap: "4px" } },
        [
          hasMatches
            ? h(ElTag, { type: "success", size: "small" }, `🎯 ${count}`)
            : h(ElTag, { type: "info", size: "small" }, `⭕ ${count}`),
        ]
      );
    },
  },
  {
    label: "匹配信息",
    prop: "match_info",
    width: 180,
    show: true,
    render: (row) => {
      if (!row.match_info) return h("span", {}, "-");
      const matchInfo = row.match_info;
      return h("div", { style: { fontSize: "12px", lineHeight: 1.5 } }, [
        h(
          "div",
          {},
          `置信度: ${((matchInfo.confidence_score || 0) * 100).toFixed(0)}%`
        ),
        matchInfo.matched_ip && h("div", {}, `IP: ${matchInfo.matched_ip}`),
      ]);
    },
  },
  {
    label: "CVSS分数",
    prop: "cvss_score",
    width: 100,
    show: true,
    render: (row) => {
      const score = row.cvss_score;
      if (!score) return h("span", {}, "-");
      const color =
        score >= 9
          ? "#ff4d4f"
          : score >= 7
          ? "#ff7a45"
          : score >= 4
          ? "#faad14"
          : "#52c41a";
      return h("span", { style: { color, fontWeight: "bold" } }, score);
    },
  },
  // {
  //   label: "来源",
  //   prop: "source",
  //   width: 100,
  //   show: true,
  // },
  {
    label: "创建时间",
    prop: "created_at",
    width: 180,
    show: true,
    render: (row) => {
      return h("span", {}, row.created_at || row.published_date || "-");
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 280,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

const showUploadDialog = ref(false);
const showPocDialog = ref(false);
const uploadFormRef = ref<DynamicFormInstance>();
const pocFormRef = ref<DynamicFormInstance>();
const selectedRows = ref<any[]>([]); // 选中的行

// 上传表单数据
const uploadFormData = reactive({
  source: "自定义",
  vul_name: "",
  vul_id: "",
  vul_level: "",
  description: "",
  cve_id: "",
  cvss_score: "",
  published_date: "",
  affected_products: "",
  product_name: "",
  service_type: "",
  version_info: "",
  has_poc: false,
  has_exploit: false,
});

// POC推荐表单数据
const pocFormData = reactive({
  intelligence_id: "",
  recommendation_mode: "all",
  min_score: 0.7,
  max_results: 10,
});

// 当前POC推荐的情报
const currentPocIntelligence = ref<any>(null);

// 上传表单配置
const uploadFormConfig: FormItemConfig[] = [
  {
    key: "source",
    name: "情报来源",
    type: "select",
    labelWidth: "120px",
    placeholder: "选择情报来源",
    rules: [{ required: true, message: "请选择情报来源" }],
    params: {
      options: [
        { label: "自定义", value: "自定义" },
        { label: "NVD", value: "NVD" },
        { label: "CNVD", value: "CNVD" },
      ],
    },
  },
  {
    key: "vul_name",
    name: "漏洞名称",
    type: "input",
    labelWidth: "120px",
    placeholder: "请输入漏洞名称",
    rules: [{ required: true, message: "请输入漏洞名称" }],
  },
  {
    key: "vul_id",
    name: "漏洞ID",
    type: "input",
    labelWidth: "120px",
    placeholder: "请输入漏洞ID",
    rules: [{ required: true, message: "请输入漏洞ID" }],
  },
  {
    key: "vul_level",
    name: "危险等级",
    type: "select",
    labelWidth: "120px",
    placeholder: "选择危险等级",
    params: {
      options: [
        { label: "严重", value: "严重" },
        { label: "高危", value: "高危" },
        { label: "中危", value: "中危" },
        { label: "低危", value: "低危" },
      ],
    },
  },
  {
    key: "cve_id",
    name: "CVE编号",
    type: "input",
    labelWidth: "120px",
    placeholder: "请输入CVE编号（可选）",
  },
  {
    key: "cvss_score",
    name: "CVSS分数",
    type: "input",
    labelWidth: "120px",
    placeholder: "请输入CVSS分数（0-10）",
  },
  {
    key: "affected_products",
    name: "影响产品",
    type: "input",
    labelWidth: "120px",
    placeholder: "请输入影响产品（可选）",
  },
  {
    key: "description",
    name: "漏洞描述",
    type: "textarea",
    labelWidth: "120px",
    placeholder: "请输入漏洞描述（可选）",
    params: {
      rows: 4,
    },
  },
  {
    key: "product_name",
    name: "产品名称",
    type: "input",
    labelWidth: "120px",
    placeholder: "匹配关键词-产品名称（可选）",
  },
  {
    key: "service_type",
    name: "服务类型",
    type: "input",
    labelWidth: "120px",
    placeholder: "匹配关键词-服务类型（可选）",
  },
  {
    key: "version_info",
    name: "版本信息",
    type: "input",
    labelWidth: "120px",
    placeholder: "匹配关键词-版本信息（可选）",
  },
  {
    key: "has_poc",
    name: "是否有POC",
    type: "switch",
    labelWidth: "120px",
  },
  {
    key: "has_exploit",
    name: "是否有利用代码",
    type: "switch",
    labelWidth: "120px",
  },
];

// 判断是否有匹配资产
const hasMatchedAssets = (row: any) => {
  return row.has_matches || (row.matched_assets && row.matched_assets > 0);
};

// POC推荐表单配置
const pocFormConfig: FormItemConfig[] = [
  {
    key: "intelligence_id",
    name: "情报ID",
    type: "input",
    labelWidth: "120px",
    placeholder: "情报ID",
    params: {
      disabled: true,
    },
  },
  {
    key: "recommendation_mode",
    name: "推荐模式",
    type: "select",
    labelWidth: "120px",
    placeholder: "选择推荐模式",
    rules: [{ required: true, message: "请选择推荐模式" }],
    options: [
      {
        label: "精确匹配 (exact)",
        value: "exact",
      },
      {
        label: "模糊匹配 (fuzzy)",
        value: "fuzzy",
      },
      {
        label: "全部模式 (all)",
        value: "all",
      },
    ],
  },
  {
    key: "min_score",
    name: "最小推荐分数",
    type: "slider",
    labelWidth: "120px",
    params: {
      min: 0,
      max: 1,
      step: 0.1,
      showStops: true,
      showInput: true,
      formatTooltip: (val: number) => val.toFixed(1),
    },
  },
  {
    key: "max_results",
    name: "最大返回数量",
    type: "number",
    labelWidth: "120px",
    placeholder: "请输入最大返回数量",
    rules: [
      { required: true, message: "请输入最大返回数量" },
      { type: "number", min: 1, max: 100, message: "数量必须在1-100之间" },
    ],
    params: {
      min: 1,
      max: 100,
      precision: 0,
    },
  },
];

const fetchIntelligenceList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };

    // 🔥 新功能：关键词搜索
    if (searchForm.search_keyword) {
      params.search_keyword = searchForm.search_keyword;
    }

    // 🔥 新功能：资产匹配筛选
    if (searchForm.has_matched_assets !== null) {
      params.has_matched_assets = searchForm.has_matched_assets;
    }

    // 🔥 新功能：快速时间筛选
    if (searchForm.time_filter) {
      params.time_filter = searchForm.time_filter;
    }

    // 🔥 新功能：精确时间范围
    if (searchForm.date_range) {
      params.date_range = searchForm.date_range;
    }

    if (searchForm.source) {
      params.source = searchForm.source;
    }
    if (searchForm.severity) {
      params.severity = searchForm.severity;
    }
    if (searchForm.has_poc !== undefined) {
      params.has_poc = searchForm.has_poc;
    }

    const { data } = await getIntelligenceHistory(params);

    // 更新列表数据（使用新数据结构）
    intelligenceList.value = data?.items || [];
    pagination.total = data?.total || data?.pagination?.total_items || 0;

    // 🆕 更新筛选统计摘要（根据MD文档设计）
    if (data?.filter_summary) {
      filterSummary.value = {
        total_matched: data.filter_summary.total_matched || 0,
        total_unmatched: data.filter_summary.total_unmatched || 0,
        severity_distribution: data.filter_summary.severity_distribution || {
          critical: 0,
          high: 0,
          medium: 0,
          low: 0,
        },
        applied_filters: data.filter_summary.applied_filters || {},
      };

      // 同时更新统计信息（兼容）
      statistics.value = {
        total_count: pagination.total,
        critical_count:
          data.filter_summary.severity_distribution?.critical || 0,
        high_count: data.filter_summary.severity_distribution?.high || 0,
        medium_count: data.filter_summary.severity_distribution?.medium || 0,
        low_count: data.filter_summary.severity_distribution?.low || 0,
      };
    } else if (data?.filters) {
      // 兼容旧数据结构
      statistics.value = {
        total_count: data.filters.total_count || 0,
        critical_count: data.filters.critical_count || 0,
        high_count: data.filters.high_count || 0,
        medium_count: data.filters.medium_count || 0,
        low_count: data.filters.low_count || 0,
      };
    }

    // 更新分页信息
    if (data?.pagination) {
      pagination.currentPage =
        data.pagination.current_page || pagination.currentPage;
      pagination.pageSize = data.pagination.page_size || pagination.pageSize;
    }
  } catch (error) {
    ElMessage.error("获取情报列表失败");
    console.error("API调用失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleSearch = (value: any) => {
  Object.assign(searchForm, value);
  pagination.currentPage = 1;
  fetchIntelligenceList();
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  Object.assign(searchForm, {
    search_keyword: "",
    source: "",
    severity: "",
    has_matched_assets: null,
    time_filter: "",
    date_range: null,
    has_poc: undefined,
  });
  pagination.currentPage = 1;
  fetchIntelligenceList();
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchIntelligenceList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchIntelligenceList();
};

const handleViewDetail = (row: any) => {
  // 跳转时传递task参数，以便返回时能保留
  const task = props.task;
  const intelligenceId = row.vul_id;
  router.push({
    name: "IntelligenceDetail",
    params: { id: intelligenceId },
    query: task ? { task } : {},
  });
};

// 单个情报匹配
const handleMatch = async (row: any) => {
  const intelligenceId = row.id || row.intelligence_id;
  const vulName = row.vul_name || row.cve_id || "该情报";

  ElMessageBox.confirm(
    `确定要执行情报 "${vulName}" 的匹配吗？`,
    "执行情报匹配",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    }
  )
    .then(async () => {
      try {
        await matchIntelligence({
          intelligence_ids: [parseInt(String(intelligenceId))],
          match_all_assets: true,
        });
        ElMessage.success("匹配执行成功");
        fetchIntelligenceList();
      } catch (error) {
        ElMessage.error("匹配执行失败");
        console.error("匹配执行失败:", error);
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 批量匹配
const handleBatchMatch = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一个情报");
    return;
  }

  const intelligenceIds = selectedRows.value.map((row) =>
    parseInt(String(row.id || row.intelligence_id))
  );

  ElMessageBox.confirm(
    `确定要批量执行 ${intelligenceIds.length} 个情报的匹配吗？`,
    "批量执行情报匹配",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    }
  )
    .then(async () => {
      try {
        await matchIntelligence({
          intelligence_ids: intelligenceIds,
          match_all_assets: true,
        });
        ElMessage.success(
          `批量匹配执行成功，共处理 ${intelligenceIds.length} 个情报`
        );
        selectedRows.value = [];
        fetchIntelligenceList();
      } catch (error) {
        ElMessage.error("批量匹配执行失败");
        console.error("批量匹配执行失败:", error);
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 处理行选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

const handleRecommendPocs = async (row: any) => {
  const intelligenceId = row.id || row.intelligence_id;
  ElMessageBox.confirm(
    `确定要为情报 "${row.vul_name}" 推荐POC吗？`,
    "POC推荐确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    }
  ).then(async () => {
    try {
      const { data } = await recommendPocs({
        intelligence_id: intelligenceId,
        recommendation_mode: "all",
        min_score: 0.7,
        max_results: 10,
      });
      ElMessage.success(
        `POC推荐完成，共推荐 ${
          data?.recommendation_summary?.recommended_count || 0
        } 个POC`
      );
      // 刷新列表
      fetchIntelligenceList();
    } catch (error) {
      ElMessage.error("POC推荐失败");
    }
  });
};

// POC推荐表单处理函数
const handleRecommendPoc = (row: any) => {
  currentPocIntelligence.value = row;
  const intelligenceId = row.id || row.intelligence_id;
  Object.assign(pocFormData, {
    intelligence_id: intelligenceId,
    recommendation_mode: "all",
    min_score: 0.7,
    max_results: 10,
  });
  showPocDialog.value = true;
};

const handleSubmitPoc = async (submitData: any) => {
  try {
    const response = await recommendPocs(submitData);
    ElMessage.success("POC推荐成功");
    showPocDialog.value = false;
    // 可以在这里处理推荐结果
    console.log("POC推荐结果:", response);
  } catch (error) {
    ElMessage.error("POC推荐失败");
    console.error("POC推荐失败:", error);
  }
};

const handleClosePocDialog = () => {
  showPocDialog.value = false;
  pocFormRef.value?.resetFields();
  Object.assign(pocFormData, {
    intelligence_id: "",
    recommendation_mode: "all",
    min_score: 0.7,
    max_results: 10,
  });
  currentPocIntelligence.value = null;
};

const handleUpload = () => {
  Object.assign(uploadFormData, {
    source: "自定义",
    vul_name: "",
    vul_id: "",
    vul_level: "",
    description: "",
    cve_id: "",
    cvss_score: "",
    published_date: "",
    affected_products: "",
    product_name: "",
    service_type: "",
    version_info: "",
    has_poc: false,
    has_exploit: false,
  });
  showUploadDialog.value = true;
};

const handleSubmitUpload = async (submitData: any) => {
  try {
    // 构造上传数据结构
    const uploadData = {
      source: submitData.source || "自定义",
      intelligence_data: [
        {
          vul_name: submitData.vul_name,
          vul_id: submitData.vul_id,
          vul_level: submitData.vul_level,
          description: submitData.description || "",
          cve_id: submitData.cve_id || "",
          cvss_score: submitData.cvss_score
            ? parseFloat(submitData.cvss_score)
            : undefined,
          published_date: submitData.published_date || "",
          affected_products: submitData.affected_products || "",
          keywords: {
            product_name: submitData.product_name || "",
            service_type: submitData.service_type || "",
            version_info: submitData.version_info || "",
          },
          has_poc: submitData.has_poc || false,
          has_exploit: submitData.has_exploit || false,
        },
      ],
    };

    await uploadIntelligence(uploadData);
    ElMessage.success("情报上传成功");
    showUploadDialog.value = false;
    fetchIntelligenceList();
  } catch (error) {
    ElMessage.error("情报上传失败");
  }
};

const handleCloseUploadDialog = () => {
  showUploadDialog.value = false;
  uploadFormRef.value?.resetFields();
  Object.assign(uploadFormData, {
    source: "自定义",
    vul_name: "",
    vul_id: "",
    vul_level: "",
    description: "",
    cve_id: "",
    cvss_score: "",
    published_date: "",
    affected_products: "",
    product_name: "",
    service_type: "",
    version_info: "",
    has_poc: false,
    has_exploit: false,
  });
};

onMounted(() => {
  fetchIntelligenceList();
});
</script>

<template>
  <div>
    <!-- 🆕 筛选统计摘要（根据MD文档设计） -->
    <el-card
      v-if="
        filterSummary.applied_filters &&
        Object.keys(filterSummary.applied_filters).length > 0
      "
      shadow="hover"
      style="margin-bottom: 16px"
    >
      <template #header>
        <span>📋 筛选统计摘要</span>
      </template>
      <div
        style="
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
          gap: 16px;
        "
      >
        <div style="text-align: center">
          <div style="font-size: 20px; font-weight: bold; color: #67c23a">
            {{ filterSummary.total_matched }}
          </div>
          <div style="font-size: 12px; color: #666; margin-top: 4px">
            有匹配资产
          </div>
        </div>
        <div style="text-align: center">
          <div style="font-size: 20px; font-weight: bold; color: #909399">
            {{ filterSummary.total_unmatched }}
          </div>
          <div style="font-size: 12px; color: #666; margin-top: 4px">
            无匹配资产
          </div>
        </div>
        <div style="text-align: center">
          <div style="font-size: 20px; font-weight: bold; color: #ff4d4f">
            {{ filterSummary.severity_distribution.critical }}
          </div>
          <div style="font-size: 12px; color: #666; margin-top: 4px">严重</div>
        </div>
        <div style="text-align: center">
          <div style="font-size: 20px; font-weight: bold; color: #ff7a45">
            {{ filterSummary.severity_distribution.high }}
          </div>
          <div style="font-size: 12px; color: #666; margin-top: 4px">高危</div>
        </div>
        <div style="text-align: center">
          <div style="font-size: 20px; font-weight: bold; color: #faad14">
            {{ filterSummary.severity_distribution.medium }}
          </div>
          <div style="font-size: 12px; color: #666; margin-top: 4px">中危</div>
        </div>
        <div style="text-align: center">
          <div style="font-size: 20px; font-weight: bold; color: #52c41a">
            {{ filterSummary.severity_distribution.low }}
          </div>
          <div style="font-size: 12px; color: #666; margin-top: 4px">低危</div>
        </div>
      </div>
    </el-card>

    <!-- 统计信息卡片 -->
    <!-- <el-card shadow="hover" style="margin-bottom: 16px">
      <template #header>
        <div style="margin-bottom: 10px">情报统计</div>
      </template>
      <div
        style="
          display: grid;
          grid-template-columns: repeat(5, 1fr);
          gap: 20px;
          text-align: center;
        "
      >
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #409eff">
            {{ statistics.total_count }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">总数</div>
        </div>
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #ff4d4f">
            {{ statistics.critical_count }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">严重</div>
        </div>
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #ff7a45">
            {{ statistics.high_count }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">高危</div>
        </div>
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #faad14">
            {{ statistics.medium_count }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">中危</div>
        </div>
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #52c41a">
            {{ statistics.low_count }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">低危</div>
        </div>
      </div>
    </el-card> -->

    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable
        :columns="columns"
        :data="intelligenceList"
        :loading="loading"
        :pagination="pagination"
        :show-toolbar="true"
        selection-type="multiple"
        row-key="id"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleUpload"> 上传情报 </el-button>
          <el-button
            type="success"
            :disabled="selectedRows.length === 0"
            @click="handleBatchMatch"
          >
            批量匹配
          </el-button>
        </template>

        <template #action="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
          <el-button type="success" size="small" @click="handleMatch(row)">
            执行匹配
          </el-button>
          <el-button
            type="warning"
            size="small"
            :disabled="!hasMatchedAssets(row)"
            @click="handleRecommendPoc(row)"
          >
            推荐POC
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 上传情报对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传漏洞情报"
      width="800px"
      @close="handleCloseUploadDialog"
    >
      <DynamicForm
        ref="uploadFormRef"
        v-model="uploadFormData"
        :form-config="uploadFormConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmitUpload"
        @cancel="handleCloseUploadDialog"
      />
    </el-dialog>

    <!-- POC推荐对话框 -->
    <el-dialog
      v-model="showPocDialog"
      title="POC推荐分析"
      width="700px"
      @close="handleClosePocDialog"
    >
      <div v-if="currentPocIntelligence" style="margin-bottom: 20px">
        <el-card shadow="never" style="background: #f5f7fa">
          <div style="font-weight: bold; margin-bottom: 8px">情报信息：</div>
          <div>
            情报ID：{{
              currentPocIntelligence.id ||
              currentPocIntelligence.intelligence_id
            }}
          </div>
          <div>漏洞名称：{{ currentPocIntelligence.vul_name }}</div>
          <div>
            危险等级：{{
              currentPocIntelligence.severity ||
              currentPocIntelligence.vul_level
            }}
          </div>
        </el-card>
      </div>

      <el-alert
        title="推荐模式说明"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <template #default>
          <div style="font-size: 14px; line-height: 1.6">
            <div>
              <strong>精确匹配 (exact)：</strong
              >精确匹配情报特征，推荐最相关的POC
            </div>
            <div>
              <strong>模糊匹配 (fuzzy)：</strong
              >模糊匹配相关特征，推荐更多可能的POC
            </div>
            <div>
              <strong>全部模式 (all)：</strong
              >使用所有推荐模式，获得最全面的POC推荐
            </div>
          </div>
        </template>
      </el-alert>

      <DynamicForm
        ref="pocFormRef"
        v-model="pocFormData"
        :form-config="pocFormConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmitPoc"
        @cancel="handleClosePocDialog"
      />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
